﻿IF EXISTS (SELECT *  FROM sys.objects  WHERE object_id = OBJECT_ID(N'fn_DistanceBetween') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
	DROP FUNCTION fn_DistanceBetween
GO

CREATE FUNCTION fn_DistanceBetween 
	(@LatitudeA 	FLOAT = NULL, 
	 @LongitudeA 	FLOAT = NULL,
	 @LatitudeB 	FLOAT = NULL, 
	 @LongitudeB 	FLOAT = NULL
	 )
RETURNS FLOAT
AS
/*
	by: jerry
	on: jul 08
	to: determine geo distance between
	note: returns feet
*/
BEGIN
	DECLARE @Feet FLOAT

	IF (@LatitudeA = @LatitudeB AND @LongitudeA = @LongitudeB)
		BEGIN
			SET @Feet = 0
		END	
	ELSE
		BEGIN

		-- use big circles math	
		DECLARE @Distance FLOAT
		SET @Distance = (SIN(RADIANS(@LatitudeA)) *
				  SIN(RADIANS(@LatitudeB)) +
				  COS(RADIANS(@LatitudeA)) *
				  COS(RADIANS(@LatitudeB)) *
				  COS(RADIANS(@LongitudeA - @LongitudeB)))

		--Get distance in miles
		DECLARE @Miles FLOAT
  		SET @Miles = DEGREES(ACOS(@Distance)) * 69.09
	
		-- convert to feet
		SET @Feet = @Miles * 5280
	END

	-- return
	RETURN @Feet
END


